package com.transcargo.action;

import java.sql.SQLException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.transcargo.errors.ErrorList;
import com.transcargo.db.db;
import com.transcargo.db.dbException;
import com.transcargo.data.Cache;

public class AddTruckAction extends AuthAction {
    private String cargo_type = "";
    private String volume = "";
    private String tonnage = "";
    private String length = "";
    private String height = "";
    private String width = "";
    private String tir = "";
    private String ekmt = "";
    private String adr = "";
    private String name = "";
    private String loading = "";
    private int id = 0;

    private void servletGetValues(HttpServletRequest request) throws ServletParametersException {
        cargo_type = request.getParameter("cargo_type");
        volume = request.getParameter("volume");
        tonnage = request.getParameter("tonnage");
        length = request.getParameter("length");
        height = request.getParameter("height");
        width = request.getParameter("width");
        tir = request.getParameter("tir");
        ekmt = request.getParameter("ekmt");
        adr = request.getParameter("adr");
        if (tir != null && tir.equals("on")) tir="1"; else tir="0";
        if (ekmt != null && ekmt.equals("on")) ekmt="1"; else ekmt="0";

        Iterator<String> it = Cache.getTransportLoadings().keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            String b = request.getParameter("load" + key);
            if (b != null && b.equals("on")) loading = loading.concat(loading.length() > 0 ? "," + key : key);
        }
    }
    private void servletValidateValues() throws ServletValidationException {
        try {
            if (length.length() > 0) {
                length = length.replace(",", ".");
                if (Float.parseFloat(length) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_LENGTH);
            }

        } catch (NumberFormatException e) {
            throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_LENGTH);
        }
        try {
            if (width.length() > 0) {
                width = width.replace(",", ".");
                if (Float.parseFloat(width) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_WIDTH);
            }

        } catch (NumberFormatException e) {
            throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_WIDTH);
        }
        try {
            if (height.length() > 0) {
                height = height.replace(",", ".");
                if (Float.parseFloat(height) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_HEIGHT);
            }

        } catch (NumberFormatException e) {
            throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_HEIGHT);
        }

        if (cargo_type.length() == 0 || Integer.parseInt(cargo_type) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_CARGO);
        if (loading.length() == 0) throw new ServletValidationException(ErrorList.ERROR_STR_LOADING_MISSING);
        if (volume.length() == 0 || Integer.parseInt(volume) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_VOLUME_MISSING);
        if (tonnage.length() == 0 || Integer.parseInt(tonnage) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_TONNAGE_MISSING);
        if (adr.length() > 1 && (Integer.parseInt(adr) == 0 || Integer.parseInt(adr) > 9)) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_ADR);
    }

    private void servletExecuteAction() throws ServletActionException {
        db.PreStatement pre = null;
        try {
            name = Cache.getTransportTypes().get(cargo_type) + "/" + volume + "/" + tonnage;
            iter = null;
            int k = 1;
            String name_alt = name;
            do {
                list = dbase.execute("SELECT id from transport WHERE user_id=" + Integer.toString(User_Id) + " and name='" + name_alt + "'");
                if (list != null) iter = list.iterator();
                if (iter.hasNext()) {
                    name_alt = name + "_(" + Integer.toString(k) + ")";
                    k++;
                }
            } while (iter.hasNext());
            name = name_alt;
            pre = dbase.CreateStatement("SELECT CreateTruck(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            pre.Insert(User_Id);
            pre.Insert(name);
            pre.Insert(cargo_type);
            pre.Insert(loading);
            if (height != null && height.length() > 0) pre.Insert(Float.parseFloat(height)); else pre.Insert(null);
            if (width != null && width.length() > 0)pre.Insert(Float.parseFloat(width)); else pre.Insert(null);
            if (length != null && length.length() > 0)pre.Insert(Float.parseFloat(length)); else pre.Insert(null);
            pre.Insert(tir);
            pre.Insert(ekmt);
            if (adr != null && adr.length() > 0) pre.Insert(Integer.parseInt(adr)); else pre.Insert(0);
            pre.Insert(Integer.parseInt(tonnage));
            pre.Insert(Integer.parseInt(volume));
            list = dbase.execute(pre);
            if (list != null) {
                iter = list.iterator();
                if (iter.hasNext()) {
                    String[] ctr = iter.next();
                    if (ctr[0].length() > 0) id = Integer.parseInt(ctr[0]);
                }
            }
            if (id == 0) throw new ServletActionException();
        } catch (SQLException e) {
			System.out.println("SQL exception: " + e.getMessage());
			throw new ServletActionException();
		} catch (dbException e) {
			System.out.println("Db exception: " + e.getMessage());
			throw new ServletActionException();
		}
    }
    public void processAction(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		try {
            servletGetValues(request);
            servletValidateValues();
            servletExecuteAction();
            sendRedirect(response, "truckname.jsp?id=" + id);
	    } catch (ServletParametersException e) {
            if (e.getMessage() != null) {
                sendError(response, new Exception(e.getMessage()));
            } else {
                sendRedirect(response, "trucks.jsp");
            }
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletActionException e) {
            sendError(response, new Exception("" + ErrorList.ERROR_STR_GENERIC + dbase.getError()));
        }
    }
}
